import { _decorator, Component, Node, Prefab, instantiate, UITransform } from 'cc';
const { ccclass, property } = _decorator;
import methods from 'db://assets/common/methods'
import config from "db://assets/common/config";
import renderExample from "db://assets/common/renderExample";
import armsMap from "db://assets/common/arms";
import { Arms } from "db://assets/common/arms/type";
import myArmsList from "db://assets/common/user/myArmsList";

@ccclass('render')
export class render extends Component {

    @property(Prefab)
    zi_wei: Prefab = null
    @property(Prefab)
    shen_sheng: Prefab = null
    @property(Prefab)
    zhen_hong: Prefab = null
    arms_Node: Map<string, Node> = new Map()
    win_w: number = config.win_w;
    win_h: number = config.win_h;
    @property(Node)
    enemyParentNode: Node = null
    enemy_Node: any = null
    enemy_item_Node: Map<string, Node> = new Map()

    hps: Node[] = []

    start() {

        for(let myArms of myArmsList.get()) {
            let uuid = methods.getUUID()
            this.arms_Node.set(uuid, instantiate(this[myArms.uuid]))
            let i: Arms = armsMap.get(myArms.uuid)
            this.arms_Node.get(uuid).x = 0
            this.arms_Node.get(uuid).y = 0
            this.arms_Node.get(uuid).uuids = uuid
            this.arms_Node.get(uuid).angle = methods.calculateAngle(this.arms_Node.get(uuid).x, this.arms_Node.get(uuid).y, this.win_w / 2 + 100, this.win_h / 2 + 100)
            this.arms_Node.get(uuid).getComponent(UITransform).setContentSize(40, 40)

            this.arms_Node.get(uuid).armsAttr = {
                attackPower: i.attr.attack + (i.attr.attack * i.attr.damageBonus + i.growthRate.damageBonus * (myArms.number - 1)) + i.growthRate.attack * (myArms.number - 1),
                hui_xin: i.attr.hui_xin + i.growthRate.hui_xin * (myArms.number - 1),
                hui_xiao: i.attr.hui_xiao + i.growthRate.hui_xiao * (myArms.number - 1),
                xi_xue: i.attr.xi_xue + i.growthRate.xi_xue * (myArms.number - 1),
                speed: i.attr.speed - i.growthRate.speed * (myArms.number - 1),
                enemyUUid: null,
                attacking: false
            }
            this.arms_Node.get(uuid).movePosition = null
            this.arms_Node.get(uuid).setParent(this.node)
        }

        this.enemy_Node = this.enemyParentNode.components[0]
        // @ts-ignore
        this.enemy_item_Node = this.enemyParentNode.components[0].enemy_item_Node
    }

    // 定义计时器变量（需在类中声明）
    private timer: number = 0;
    update(deltaTime: number) {
        // 累加计时器
        this.timer += deltaTime;
        // 当计时器超过间隔时间时执行逻辑
        if (this.timer >= config.fps) {
            // 执行你的逻辑（每秒一次）
            this.doSomething();

            // 重置计时器（或减去间隔时间以保持精度）
            this.timer = 0;
            // 或：this.timer -= this.interval; // 更精确，但可能累积误差
        }
    }

    setMovePosition(p0: { x: number, y: number }, quadrant: number, speed: number) {
        let movePosition = methods.getRandomPointOnCircle(300, quadrant, p0.x, p0.y)
        return  {
            start: methods.getStartEndPoint(p0, movePosition.point)[0],
            end: methods.getStartEndPoint(p0, movePosition.point)[1],
            type: 1,
            index: 0,
            speed,
            quadrant: movePosition.quadrant, // 直接返回传入的象限作为点所在的象限
            randomDegree: movePosition.randomDegree // 返回生成的角度
        }
    }

    private doSomething() {
        // 每秒执行一次的代码
        for(let i of this.arms_Node) {
            let exNode = i[1]
            if(this.enemy_item_Node.size !== 0) {
                if(!exNode.armsAttr.enemyUUid) {
                    exNode.armsAttr.enemyUUid = this.enemy_Node.getRandomEnemy()[0]
                }
                if(!exNode.movePosition && exNode.armsAttr.enemyUUid) {
                    exNode.movePosition = this.setMovePosition({
                        x: this.enemy_item_Node.get(exNode.armsAttr.enemyUUid).x,
                        y: this.enemy_item_Node.get(exNode.armsAttr.enemyUUid).y
                    }, 1, exNode.armsAttr.speed)
                }
                if(!this.enemy_item_Node.get(exNode.armsAttr.enemyUUid)) {
                    exNode.armsAttr.enemyUUid = null
                    exNode.armsAttr.attacking = false
                    continue;
                }

                if(exNode.armsAttr.attacking) {
                    // 获取敌人节点并缓存，避免重复查找
                    const enemyNode = this.enemy_item_Node.get(exNode.armsAttr.enemyUUid);
                    if (!enemyNode) {
                        exNode.armsAttr.enemyUUid = null
                        exNode.armsAttr.attacking = false
                        return
                    } // 安全检查：如果敌人节点不存在则退出

                    // 根据移动类型执行不同的移动逻辑
                    const { type, index, start, end, speed } = exNode.movePosition;
                    const targetPosition = type === 1 ? start : end;

                    // 计算下一个移动点
                    exNode.movePosition.index += 1;
                    const nextPoint = methods.attackPath2(
                        enemyNode.x,
                        enemyNode.y,
                        targetPosition.x,
                        targetPosition.y,
                        speed,
                        exNode.movePosition.index
                    );
                    // 更新位置和角度
                    exNode.angle = methods.calculateAngle(exNode.x, exNode.y, nextPoint.x, nextPoint.y);
                    exNode.x = nextPoint.x;
                    exNode.y = nextPoint.y;
                    // 检查是否完成当前阶段移动
                    if (exNode.movePosition.index >= speed) {
                        // 重置计数器并切换移动类型
                        exNode.movePosition.index = 0;
                        exNode.movePosition.type = type === 1 ? 2 : 1;

                        // 生成HP显示
                        const enemyX = enemyNode.x;
                        const enemyY = enemyNode.y;
                        // exNode.armsAttr.attackPower
                        let hpVal = exNode.armsAttr.attackPower
                        let hpText = exNode.armsAttr.attackPower
                        if(methods.getRandomNumber(0, 100) <= exNode.armsAttr.hui_xin * 100) {
                            hpVal = Math.floor(exNode.armsAttr.attackPower * exNode.armsAttr.hui_xiao)
                            hpText = '会心 ' + hpVal
                        }else {
                            hpVal = Math.floor(exNode.armsAttr.attackPower)
                            hpText = hpVal
                        }
                        const hp = renderExample.renderHp(hpText, enemyX, enemyY);
                        this.node.addChild(hp);
                        this.hps.push(hp);
                        enemyNode.enemyAttr.hp -= hpVal
                        // 重新设置移动位置（修复了原代码中的赋值问题）
                        exNode.movePosition = this.setMovePosition({ x: enemyX, y: enemyY }, exNode.movePosition.quadrant, exNode.armsAttr.speed);
                    }
                }else {
                    if(this.enemy_item_Node.get(exNode.armsAttr.enemyUUid)) {
                        exNode.angle = methods.calculateAngle(exNode.x, exNode.y, this.enemy_item_Node.get(exNode.armsAttr.enemyUUid).x, this.enemy_item_Node.get(exNode.armsAttr.enemyUUid).y)
                        methods.nextPosition(exNode.x, exNode.y, this.enemy_item_Node.get(exNode.armsAttr.enemyUUid).x, this.enemy_item_Node.get(exNode.armsAttr.enemyUUid).y, 200 / exNode.armsAttr.speed).then(res => {
                            // @ts-ignore
                            exNode.x = res.x
                            // @ts-ignore
                            exNode.y = res.y
                        }).catch(res => {
                            exNode.armsAttr.attacking = true
                        })
                    }
                }
            }else {
                exNode.angle = methods.calculateAngle(exNode.x, exNode.y, 0, 0)
                methods.nextPosition(exNode.x, exNode.y, 0, 0, 200 / exNode.armsAttr.speed).then(res => {
                    // @ts-ignore
                    exNode.x = res.x
                    // @ts-ignore
                    exNode.y = res.y
                }).catch(res => {
                    exNode.destroy()
                    this.arms_Node.delete(exNode.uuids)
                })
            }
        }
        renderExample.renderHpDestroy(this.hps)
    }
}